package com.huaifang.yan.buffer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        printText();
        printChar();
    }

    private static void printText() {

        ByteBuffer buffer = ByteBuffer.allocate(10);
        String text = "这是一片优美的文章...";
        int writerSize = 6;

        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);

        for (int i = 0; i < bytes.length; i = i + writerSize) {
            int length = Math.min(writerSize, bytes.length - i); // 确保不会越界
            buffer.put(bytes, i, length);
            buffer.flip();
            int limit = buffer.limit();
            byte[] read = new byte[limit];
            buffer.get(read, 0, limit);
            System.out.println(new String(read, StandardCharsets.UTF_8));
            buffer.clear();
        }
    }

    private static void printChar() {

        ByteBuffer buffer = ByteBuffer.allocate(10);
        String text = "asdbsdfhgjgwr";

        int writerSize = 1;
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);

        for (int i = 0; i < bytes.length; i = i + writerSize) {
            int length = Math.min(writerSize, bytes.length - i); // 确保不会越界
            buffer.put(bytes, i, length);
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }
            buffer.clear();
        }
        System.out.println();
    }
}